<template>
  <div class="app-container">
    <el-container>
      <!-- 左侧部门树形菜单列表 -->
      <el-aside style="padding: 10px 0px 0px 0px;
          background: #fff;
          border-right: 0px solid #dfe6ec;" width="200px">
        <el-tree style="font-size: 14px" ref="leftTree" :data="deptList" node-key="id" :props="defaultProps" default-expand-all empty-text="暂无数据" :show-checkbox="false" :highlight-current="true" :expand-on-click-node="false" @node-click="handleNodeClick">
          <div class="custom-tree-node" slot-scope="{ node, data }">
            <div>
              <span v-if="data.children.length == 0">
                <i class="el-icon-document"></i>
              </span>
              <span v-else @click.stop="openBtn(data)">
                <svg-icon v-if="data.open" icon-class="add-s" />
                <svg-icon v-else icon-class="sub-s" />
              </span>
              <!-- 名称 -->
              <span style="margin-left: 3px">{{ node.label }}</span>
            </div>
          </div>
        </el-tree>
      </el-aside>

      <!-- 右侧用户表格数据 -->
      <el-main>
        <!-- 查询条件 -->
        <el-form :model="userQueryParams" ref="searchForm" label-width="80px" :inline="true" size="small">
          <el-form-item label="用户名">
            <el-input v-model="userQueryParams.data.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="userQueryParams.data.realName" placeholder="请输入用户昵称" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="userQueryParams.data.phone" placeholder="请输入电话" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="search()">查询</el-button>
            <el-button icon="el-icon-delete" @click="reset()">重置</el-button>
            <el-button icon="el-icon-plus" size="small" type="success" @click="openAddWindow()">新增</el-button>
            <el-button icon="el-icon-download" type="warning" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>

        <!-- 用户表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%; margin-bottom: 10px">
          <el-table-column prop="userId" label="用户编号" width="90px"></el-table-column>
          <el-table-column prop="userName" label="用户名"></el-table-column>
          <el-table-column prop="nickName" label="用户昵称"></el-table-column>
          <el-table-column prop="deptId" label="所属部门"></el-table-column>
          <el-table-column prop="phonenumber" label="电话"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column align="center" width="290" label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button icon="el-icon-delete" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
              <el-button icon="el-icon-setting" type="primary" size="mini" @click="assignRole(scope.row)">分配角色</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页工具栏 -->
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" 
        :current-page="userQueryParams.page.current" :page-sizes="[10, 20, 30, 40, 50]" :page-size="userQueryParams.page.size" 
        layout="total, sizes, prev, pager, next, jumper" :total="userTotal" align="right">
        </el-pagination>
      </el-main>
    </el-container>
    
    <!-- 添加和编辑用户窗口 -->
    <system-dialog :title="userDialog.title" :height="userDialog.height" :width="userDialog.width" :visible="userDialog.visible" @onClose="onClose" @onConfirm="onConfirm">
      <div slot="content">
        <el-form :model="user" ref="userForm" :rules="rules" label-width="80px" :inline="true" size="small">
          <el-form-item prop="userName" label="用户名">
            <el-input v-model="user.userName" :disabled="userDisable"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码" v-if="user.userId == undefined">
            <el-input type="password" v-model="user.password" maxlength="20" show-password />
          </el-form-item>
          <el-form-item prop="deptName" label="所属部门">
            <el-input v-model="user.deptName" :readonly="true" @click.native="selectDept()"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="user.nickName"></el-input>
          </el-form-item>
          <el-form-item prop="phonenumber" label="电话">
            <el-input v-model="user.phonenumber"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item prop="sex" label="性别">
            <el-select v-model="user.sex" placeholder="请选择性别">
              <el-option label="男" value="0"></el-option>
              <el-option label="女" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item size="small" label="状态" prop="status">
            <el-radio-group v-model="user.status">
              <el-radio label="0">正常</el-radio>
              <el-radio label="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <br />
          <!-- 用户头像：待补充 -->
          <el-form-item size="small" label="头像">待完善</el-form-item>
        </el-form>
      </div>
    </system-dialog>

    <!-- 所属部门弹框 -->
    <system-dialog :title="parentDialog.title" :width="parentDialog.width" :height="parentDialog.height" :visible="parentDialog.visible" @onClose="onParentClose" @onConfirm="onParentConfirm">
      <div slot="content">
        <el-tree ref="parentTree" :data="parentList" default-expand-all node-key="deptId" :props="parentProps" :show-checkbox="false" :highlight-current="true" :expand-on-click-node="false" @node-click="parentClick">
          <div class="customer-tree-node" slot-scope="{ node, data }">
            <span v-if="data.children.length == 0">
              <i class="el-icon-document" />
            </span>
            <span v-else @click.stop="openParentBtn(data)">
              <svg-icon v-if="data.open" icon-class="add-s" />
              <svg-icon v-else icon-class="sub-s" />
            </span>
            <span style="margin-left: 3px">{{ node.label }}</span>
          </div>
        </el-tree>
      </div>
    </system-dialog>

    <!-- 分配角色窗口 -->
    <system-dialog :title="assignDialog.title" :height="assignDialog.height" :width="assignDialog.width" 
      :visible="assignDialog.visible" @onClose="onAssignClose" @onConfirm="onAssignConfirm">
      <div slot="content">
        <!-- 分配角色数据列表 -->
        <el-table ref="assignRoleTable" :data="assignRoleList" border stripe style="width: 100%; margin-bottom: 10px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="roleKey" label="角色编码" />
          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column prop="remark" label="角色备注" />
        </el-table>
        <!-- 分页工具栏 -->
        <el-pagination v-show="roleTotal>0" @size-change="assignSizeChange" @current-change="assignCurrentChange" 
          :current-page.sync="roleQueryParams.page.current" :page-sizes="[10, 20, 30, 40, 50]" :page-size="roleQueryParams.page.size" 
          layout="total, sizes, prev, pager, next, jumper" :total="roleTotal" background align="right">
        </el-pagination>
      </div>
    </system-dialog>
  </div>
</template>

<script>
import deptApi from "@/api/system/dept";
import userApi from "@/api/system/user";
import roleApi from "@/api/system/role";
//导入对话框组件
import SystemDialog from "@/components/system/SystemDialog.vue";

export default {
  name: "User",
  components: { SystemDialog },
  data() {
    return {
      //左侧部门树列表
      deptList: [],
      //树节点属性
      defaultProps: {
        children: "children",
        label: "deptName",
      },

      //表格数据列表
      tableData: [],
      //总条数
      userTotal: 0,
      // 用户列表条件查询
      userQueryParams: {
        page: {
          current: 1,
          size: 10
        },
        data: {}
      },

      //添加和修改用户窗口属性
      userDialog: {
        title: "",
        height: 410,
        width: 610,
        visible: false,
      },
      //用户对象
      user: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, trigger: "blur", message: "请输入用户名" },
        ],
        deptName: [
          { required: true, trigger: "change", message: "请选择所属部门" },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, trigger: "blur", message: "请填写登录密码" },
        ],
        nickName: [
          { required: true, trigger: "blur", message: "请填写用户昵称" },
        ],
        sex: [{ required: true, trigger: "change", message: "请选择性别" }],
        status: [{ required: true, trigger: "change", message: "请选择状态" }],
      },

      //选择所属部门窗口属性
      parentDialog: {
        title: "",
        width: 300,
        height: 450,
        visible: false,
      },
      //树节点属性
      parentProps: {
        children: "children",
        label: "deptName",
      },
      //所属部门节点数据
      parentList: [],
      userDisable: false,

      //分配角色窗口属性
      assignDialog: {
        title: "",
        visible: false,
        width: 800,
        height: 410,
      },
      // 分配角色条件查询
      roleQueryParams: {
        page: {
          current: 1,
          size: 10
        },
        data: {}
      },
      roleTotal: 0,
      //角色列表
      assignRoleList: [],
      //被选中的角色id
      selectedIds: [],
      //被分配角色的用户ID
      selectedUserId: "",
    };
  },
  created() {
    this.getDeptList();
    this.search();
  },
  methods: {
    //查询部门列表
    async getDeptList() {
      //发送查询请求
      let res = await deptApi.getDeptList(null);
      //判断是否成功
      if (res.success) {
        this.deptList = res.data;
        //树加载完成后，默认点击第一个节点
        this.$nextTick(() => {
          const firstNode = document.querySelector(".el-tree-node");
          firstNode.click();
        });
      }
    },
    //左侧树节点点击事件
    handleNodeClick(data) {
      //给部门编号赋值
      this.userQueryParams.data.deptId = data.deptId;
      //查询数据
      this.search();
    },
    openBtn(data) {
      //修改折叠展开状态
      data.open = !data.open;
      this.$refs.leftTree.store.nodesMap[data.deptId].expanded = !data.open;
    },
    // 查询用户列表
    async search() {
      //发送查询请求
      let res = await userApi.getUserPage(this.userQueryParams);
      if (res.success) {
        this.tableData = res.data.records;
        this.userTotal = res.data.total;
      }
    },
    //重置查询条件
    reset() {
      this.searchModel = {};
      this.search();
    },
    //当每页数量发生变化时触发的事件
    handleSizeChange(size) {
      this.userQueryParams.page.size = size;
      this.search();
    },
    //当页码发生变化时触发的事件
    handleCurrentChange(page) {
      this.userQueryParams.page.current = page;
      this.search();
    },
    //打开新增对话框
    openAddWindow() {
      this.$resetForm("userForm", this.user);
      this.userDisable = false;
      this.userDialog.visible = true;
      this.userDialog.title = "新增用户";
    },
    //新增或修改取消事件
    onClose() {
      this.userDialog.visible = false;
    },
    //新增或修改确认事件
    onConfirm() {
      //表单验证
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          let res = null;
          if (this.user.userId == undefined) {
            res = await userApi.addUser(this.user);
          } else {
            res = await userApi.updateUser(this.user);
          }
          if (res.success) {
            this.$message.success(res.message);
            this.search();
            this.userDialog.visible = false;
          } else {
            this.$message.error(res.message);
            this.userDialog.visible = false;
          }
        }
      });
    },
    //打开选择所属部门窗口
    async selectDept() {
      //查询上级部门数据
      let res = await deptApi.getDeptList(null);
      //判断是否成功
      if (res.success) {
        this.parentList = res.data;
      }
      //显示窗口
      this.parentDialog.visible = true;
    },
    //选择上级部门取消事件
    onParentClose() {
      this.parentDialog.visible = false;
    },
    //选择上级部门确认事件
    onParentConfirm() {
      this.parentDialog.visible = false;
    },
    //上级部门树节点点击事件
    parentClick(data) {
      this.user.deptId = data.deptId;
      this.user.deptName = data.deptName;
    },
    //上级部门树加号 减号 图标点击事件
    openParentBtn(data) {
      data.open = !data.open;
      this.$refs.parentTree.store.nodesMap[data.deptId].expanded = !data.open;
    },
    //修改按钮
    handleEdit(row) {
      this.user = row;
      this.userDisable = true;
      this.user.deptName = "111";
      this.userDialog.title = "编辑用户";
      this.userDialog.visible = true;
    },
    //删除按钮
    async handleDelete(row) {
      let confirm = await this.$myconfirm("确定要删除该数据吗?");
      if (confirm) {
        //封装条件
        let params = { userId: row.userId };
        //发送删除请求
        let res = await userApi.deleteUser(params);
        //判断是否成功
        if (res.success) {
          this.$message.success(res.message);
          //刷新
          this.search();
        } else {
          this.$message.error(res.message);
        }
      }
    },
    //用户分配角色
    async assignRole(row) {
      //防止回显出现问题
      this.selectedIds = [];
      this.selectedUserId = "";
      //被分配用户的id
      this.selectedUserId = row.userId;
      //显示窗口
      this.assignDialog.visible = true;
      //设置标题
      this.assignDialog.title = `给【${row.nickName}】分配角色`;
      //查询当前登录用户的所有角色信息
      await this.getAssignRoleList();
      //获取当前被分配用户的ID
      let params = {
        userId: row.userId,
      };
      //发送根据用户ID查询角色列表的请求
      let res = await userApi.getRoleIdByUserId(params);
      // //如果存在数据
      if (res.success && res.data) {
        //将查询到的角色ID列表交给选中角色数组
        this.selectedIds = res.data;
        //循环遍历
        this.selectedIds.forEach((key) => {
          this.assignRoleList.forEach((item) => {
            if (item.roleId === key) {
              this.$refs.assignRoleTable.toggleRowSelection(item, true);
            }
          });
        });
      }
    },
    //查询当前登录用户的所有角色信息
    async getAssignRoleList() {
      let res = await roleApi.getRolePage(this.roleQueryParams);
      if (res.success) {
        this.assignRoleList = res.data.records;
        this.roleTotal = res.data.total;
      }
    },
    //分配角色取消事件
    onAssignClose() {
      this.assignDialog.visible = false;
    },
    //分配角色确认事件
    async onAssignConfirm() {
      //判断用户是否有选中角色
      if (this.selectedIds.length === 0) {
        this.$message.warning("请选择要分配的角色！");
        return;
      }
      let params = {
        userId: this.selectedUserId,
        roleIds: this.selectedIds,
      };
      //发送请求
      let res = await userApi.assignRoleSave(params);
      //判断是否成功
      if (res.success) {
        this.$message.success(res.message);
        //关闭窗口
        this.assignDialog.visible = false;
      } else {
        this.$message.error(res.message);
      }
    },
    //当每页数量发生变化时触发该事件
    assignSizeChange(size) {
      this.roleQueryParams.data.size = size;
      this.getAssignRoleList();
    },
    //当页码发生变化时触发该事件
    assignCurrentChange(page) {
      this.roleQueryParams.data.current = page;
      this.getAssignRoleList();
    },
    //当点击多选框时触发该事件
    handleSelectionChange(rows) {
      let roleIds = [];
      //循环遍历选中的角色ID
      for (let i = 0; i < rows.length; i++) {
        //将当前选中的角色ID放到数组中
        roleIds.push(rows[i].roleId);
      }
      //将选中的角色ID交给成员变量
      this.selectedIds = roleIds;
    },
    // 导出按钮
    async handleExport() {
      if(this.total === 0) {
        return this.$message.error("查询数据为空，不能进行导出操作！");
      }
      const fname = `用户信息-${+new Date()}.xlsx`;
      var params = {};
      // this.selectionNum != 0 ? params = {"params": {"userId": this.ids}}: params = this.queryParams.data;
      let res = await userApi.exportSysUser(params);
      console.log(res,'rs');
    }
  },
};
</script>

<style lang="scss" scoped>
</style>